<template>
  <div class="report-view">
    <h1>实验报告收集与检查系统</h1>
    <ReportUpload @upload-success="fetchReports" />
    <ReportList :reports="reports" @view-report="viewReport" />
    
    <div style="text-align: center;">
      <button class="check-duplicates-btn" @click="checkDuplicates">查重并生成图</button>
    </div>
    
    <div class="chart-container" v-if="showChart">
      <canvas id="heatmapChart"></canvas>
      <canvas id="similarityChart"></canvas>
    </div>
  </div>
</template>

<script>
import ReportUpload from '../components/ReportUpload.vue';
import ReportList from '../components/ReportList.vue';
import ReportDetail from '../components/ReportDetail.vue';
import { ref,nextTick } from 'vue';
import axios from 'axios';
import { Chart, registerables } from 'chart.js';
import { MatrixController, MatrixElement } from 'chartjs-chart-matrix';

// 注册 Chart.js 和 Matrix 控制器
Chart.register(...registerables, MatrixController, MatrixElement);

export default {
  components: {
    ReportUpload,
    ReportList,
    ReportDetail,
  },
  setup() {
    const reports = ref([]);
    const selectedReport = ref(null);
    const showChart = ref(false);

    const fetchReports = async () => {
      try {
        const response = await axios.get('/api/reports');
        reports.value = response.data.reports; // 确保访问正确的字段
      } catch (error) {
        console.error('获取报告列表失败:', error);
      }
    };

    const viewReport = (report) => {
      selectedReport.value = report;
    };

    const checkDuplicates = async () => {
        try {
            const response = await axios.get('/api/reports/check-duplicates');
            const { similarityMatrix, reports: reportList } = response.data;
    
            // 生成图表数据
            const labels = reportList.map((report) => report.name);
    
            // 数据集用于雷达图
            const radarDatasets = [];
            for (let i = 0; i < similarityMatrix.length; i++) {
                radarDatasets.push({
                    label: labels[i],
                    data: similarityMatrix[i],
                    backgroundColor: `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.5)`,
                });
            }
    
            // 数据集用于热力图
            const heatmapData = {
              datasets: [
                  {
                      data: similarityMatrix.flatMap((row, rowIndex) =>
                          row.map((value, colIndex) => ({
                              x: labels[colIndex],
                              y: labels[rowIndex],
                              v: value, // 相似度值
                          }))
                      ),
                      backgroundColor: (ctx) => {
                          const value = ctx.raw.v; // 获取相似度值
                          const alpha = value; // 根据相似度调整透明度
                          return `rgba(255, 0, 0, ${alpha})`; // 红色为主色调
                      },
                      borderWidth: 1,
                      borderColor: 'rgba(255, 255, 255, 0.5)', // 白色边框
                  },
              ],
            };  
    
            // 先显示canvas
            showChart.value = true;
    
            // 等待DOM更新后再获取canvas
            await nextTick();
    
            // 绘制雷达图
            const radarCanvas = document.getElementById('similarityChart');
            if (!radarCanvas) {
                alert('未找到 similarityChart 元素');
                return;
            }
            const radarCtx = radarCanvas.getContext('2d');
            new Chart(radarCtx, {
                type: 'radar',
                data: {
                    labels,
                    datasets: radarDatasets,
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                    },
                },
            });
    
            // 绘制热力图
            const heatmapCanvas = document.getElementById('heatmapChart');
            if (!heatmapCanvas) {
                alert('未找到 heatmapChart 元素');
                return;
            }
            const heatmapCtx = heatmapCanvas.getContext('2d');
            new Chart(heatmapCtx, {
              type: 'matrix', // 使用 matrix 类型绘制热力图
              data: heatmapData,
              options: {
                  responsive: true,
                  plugins: {
                      legend: {
                          display: false, // 不显示图例
                      },
                      tooltip: {
                          callbacks: {
                              label: (ctx) => `相似度: ${ctx.raw.v.toFixed(2)}`,
                          },
                      },
                  },
                  scales: {
                      x: {
                          type: 'category',
                          labels: labels,
                          title: {
                              display: true,
                              
                          },
                      },
                      y: {
                          type: 'category',
                          labels: labels,
                          title: {
                              display: true,
                              
                          },
                      },
                  },
              },
          });
        } catch (error) {
            console.error('查重失败:', error, error.response?.data);
            alert('查重失败，请稍后重试');
        }
    };
    fetchReports(); // 在 setup 中调用以初始化数据

    return {
      reports,
      selectedReport,
      fetchReports,
      viewReport,
      checkDuplicates,
      showChart,
    };
  },
};
</script>

<style scoped>
.report-view {
  padding: 20px;
}

.check-duplicates-btn {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.check-duplicates-btn:hover {
  background-color: #0056b3;
}

.chart-container {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

canvas {
  max-width: 400px;
  max-height: 400px;
}
</style>